
// const BASE_URL = "http://localhost:7080/api/v1"
const BASE_URL = "http://120.27.147.202:7080/api/v1"

// 定义请求配置类型
interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'DELETE';
  data?: any;
  header?: any;
}

// 定义响应数据类型
interface ResponseData<T = any> {
  code: number;
  message: string;
  data: T;
}

// 定义请求函数
const request = <T = any>(options: RequestOptions): Promise<ResponseData<T>> => {
  // 获取 token
  const token = uni.getStorageSync('token');

  // 设置请求头
  const header = {
    'Content-Type': 'application/json',
    ...options.header,
  };

  if (token) {
    header.Authorization = `${token}`;
  }

  // 返回 Promise
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL +  options.url,
      method: options.method || 'GET',
      data: options.data,
      header,
      success: (res) => {
        if (res.statusCode === 200) {
          // 请求成功
          resolve(res.data as ResponseData<T>);
        } else {
          // 请求失败
          // 弹窗提示一下
          uni.showToast({
            title: "本次请求出现问题了, 请稍后再试",
            icon:"none"
          })
          reject(res.data);
        }
      },
      fail: (err) => {
        // 网络错误
        reject(err);
      },
    });
  });
};

// 封装 GET 请求
export const get = <T = any>(url: string, data?: any) => {
  return request<T>({ url, method: 'GET', data });
};

// 封装 POST 请求
export const post = <T = any>(url: string, data?: any) => {
  return request<T>({ url, method: 'POST', data });
};

// 封装 DELETE 请求
export const del = <T = any>(url: string, data?: any) => {
  return request<T>({ url, method: 'DELETE', data });
};

// 默认导出
export default request;